package controller

import (
	"Graphite/model"
	"Graphite/util"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

//func SetCK(c *gin.Context) {
//	util.SetCK(c)
//	c.JSON(http.StatusOK, gin.H{"status": "200"})
//}
//
//func SetSession(c *gin.Context)  {
//	util.SetSession(c)
//	c.JSON(http.StatusOK, gin.H{"status": "200"})
//}

func Home(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": 2000,
		"msg":  "success",
		"data": gin.H{"data": "home"},
	})
}

func ApiInsert(c *gin.Context) {
	var api model.Api
	if err := c.Bind(&api); err != nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	} else {
		util.CreateOne(c, "api", api, "url", api.Url)
		return
	}
}

func FindAllApi(c *gin.Context) {
	jsonStr, total := util.RetrieveP(c, "api", "url", "", 1, 10)
	//格式转化成结构体
	var api []model.Api
_:
	json.Unmarshal(jsonStr, &api)
	var data struct {
		Api   []model.Api;
		Total int64
	}
	data.Api = api
	data.Total = total
	util.Return(c, 200, util.SUCCESS, data)
}

func FindAllApiByNameUrlAndMethod(c *gin.Context) {
	var paging model.Paging
	var err error
	paging.Method = c.Query("method")
	paging.Page, err = strconv.ParseInt(c.Query("page"), 10, 64)
	paging.PerPage, err = strconv.ParseInt(c.Query("per_page"), 10, 64)
	paging.Key = c.Query("key")
	if err != nil {
		log.Println(err)
	}

	jsonStr, total := util.RetrievesAnd(c, "api", "url", "name", "method", paging.Key, paging.Method, paging.Page, paging.PerPage)
	//格式转化成结构体
	var api []model.Api
_:
	json.Unmarshal(jsonStr, &api)
	var data struct {
		Api   []model.Api;
		Total int64;
		Page  int64
	}
	data.Api = api
	data.Total = total
	util.Return(c, 200, util.SUCCESS, data)
}

//func FindAllApiByMethod(c *gin.Context)  {
////	var  key model.Key
////	key.Key = c.Query("key")
////	method := c.Query("method")
////	fmt.Println(key.Key)
////	jsonStr:=util.RetrievesAnd(c,"api","name","method",key.Key,method)
////	//格式转化成结构体
////	var api  []model.Api
////	_:json.Unmarshal(jsonStr,&api)
////	util.Return(c,200,util.SUCCESS,api)
////
////}

func ApiUpdate(c *gin.Context) {
	var api model.Api
	if err := c.Bind(&api); err != nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	} else {
		util.UpdateOne(c, "api", api, "_id", api.Id)
	}
}

func ApiDelete(c *gin.Context) {
	var key model.Key
	if err := c.Bind(&key); err != nil {
		util.Return(c, 200, util.PARA_ERROR, err)
		return
	} else {
		util.DeleteOne(c, "api", "_id", key.Id)
	}
}
